import 'dart:convert';

import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../common/api_service.dart';
import '../common/events.dart';
import '../common/logger.dart';
import '../model/user_model.dart';

class AuthService extends GetxService {

  UserModel? _userModel;

  UserModel? get userModel => _userModel;

  Future<AuthService> init() async {
    await getUserInfo();
    return this;
  }

  Future<void> saveUserInfo(Map<String, dynamic> data) async {
    var user = UserModel.fromJson(data);
    _userModel = user;

    String jsonString = jsonEncode(data);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("user_info", jsonString);
  }

  Future<void> getUserInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var data = prefs.getString("user_info");
    if (data != null) {
      var userMap = jsonDecode(data);
      var user = UserModel.fromJson(userMap);
      _userModel = user;
    }
  }

  bool get isLogIn {
    var token = _userModel?.token ?? "";
    return token.isNotEmpty;
  }

  void logout() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove("user_info");
    _userModel = null;
  }

  void login({required LoginType loginType, required String id, required String pwd, required Function success, required Function failure}) {
    ApiService().login(loginType, id, pwd, (model) {
      saveUserInfo(model.data);
      eventBus.fire(UserLoggedInEvent());
      success();
    }, (error) {
      logger.e(error);
      failure(error);
    });
  }
}


enum LoginType {
  guest,
  phone,
  wechat,
  qq,
  apple;

  String get value {
    switch (this) {
      case LoginType.guest:
        return 'tourist';
      case LoginType.phone:
        return 'phone';
      case LoginType.wechat:
        return 'app_wx';
      case LoginType.qq:
        return 'app_qq';
      case LoginType.apple:
        return 'apple';
      }
  }
}